import { getUserDetailById, getUserInfoApi, login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  // 放入核心的配置项
  namespaced: true, // 子模块开启命名空间
  state: {
    // 获取token
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updataToken(state, token) {
      state.token = token
      // 存储token
      setToken(token)
    },
    // 删除token
    delToken(state) {
      state.token = ''
      removeToken()
    },
    // 更新用户数据
    getUser(state, info) {
      state.userInfo = info
      // console.log(state.userInfo, 20)
    },
    // 删除数据
    delUser(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async initToken(context, fromData) {
      const res = await login(fromData)
      // console.log(res)
      // 3.判断是否请求成功，通知用户
      if (res.code !== 10000) return Message.error(res.message)
      Message.success(res.message)
      context.commit('updataToken', res.data)
    },
    async getUserInfo(context) {
      try {
        const res = await getUserInfoApi()
        // console.log(res)
        const info = await getUserDetailById(res.data.userId)
        // console.log(info)
        context.commit('getUser', { ...res.data, ...info.data })
      } catch (error) {
        console.log(error)
      }
    },
    updateUser(context) {
      context.commit('delToken')
      context.commit('delUser')
    }
  }
}
